using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Collections.Generic;
using Sce.PlayStation.Core;
using Sce.PlayStation.Core.Imaging;
using Sce.PlayStation.Core.Environment;
using Sce.PlayStation.HighLevel.UI;
using VitaReader;

namespace VitaReaderLibPS
{
	
    internal class BookList : ReaderUI
    {
		Label		UILbBookListTitle;
		Label		UILbBookListCounter;
		ImageBox	UIImgBookListBk;
        Button		UIBnBookListCancel;
        Button		UIBnBookListRefresh;
		Button		UIBnBookDelete;
		ScrollPanel	UISpBookListParent;
			ListPanel	UILpBookList;
		//	Label UILbBookInfo;
		
		
		private int mCurrentBookListItem;
		private List<Button> mBookListButton;
		private int mBookCount;
		
		#region readerUI overrides
		public override void Initialize(ReaderScene scene)
		{
			base.Initialize(scene);
			
			#region create
            mRoot = new Panel();
            mRoot.Name = "BookListRoot";
			mRoot.BackgroundColor = mScene.ListBackgroundColor;
			//mRoot.BackgroundStyle = DialogBackgroundStyle.Custom;
			//mRoot.CustomBackgroundColor = mScene.ListBackgroundColor;
			{
				UILbBookListTitle = new Label();
				UILbBookListTitle.Name = "UILbBookListTitle";
				UILbBookListTitle.Font = mScene.TitleFont;
				UILbBookListTitle.TextColor = mScene.TitleColor;
				UILbBookListTitle.HorizontalAlignment = HorizontalAlignment.Left;
				this.mRoot.AddChildLast(UILbBookListTitle);
				
				UILbBookListCounter = new Label();
				UILbBookListCounter.Name = "UILbBookListCounter";
				UILbBookListCounter.Font = mScene.FontSet.Small;
				UILbBookListCounter.TextColor = mScene.TitleColor;
				UILbBookListCounter.HorizontalAlignment = HorizontalAlignment.Right;
				this.mRoot.AddChildLast(UILbBookListCounter);
				
				
				// UIImgBookListBk
	            UIImgBookListBk = new ImageBox();
	            UIImgBookListBk.Name = "UIImgBookListBk";
	            UIImgBookListBk.Image = mScene.ListBackgroundImage;
	            UIImgBookListBk.ImageScaleType = ImageScaleType.Stretch;
				this.mRoot.AddChildFirst(UIImgBookListBk);
				
				// UIBnBookListCancel
	            UIBnBookListCancel = new Button();
	            UIBnBookListCancel.Name = "UIBnBookListCancel";
	            UIBnBookListCancel.TextColor = mScene.ButtonTextColor;
	            UIBnBookListCancel.TextFont = mScene.ButtonTextFont;
	            UIBnBookListCancel.Style = ButtonStyle.Custom;
	            UIBnBookListCancel.CustomImage = mScene.mButtonImage;
				this.mRoot.AddChildLast(UIBnBookListCancel);
				
				// UIBnBookListRefresh
	            UIBnBookListRefresh = new Button();
	            UIBnBookListRefresh.Name = "UIBnBookListRefresh";
	            UIBnBookListRefresh.TextColor = mScene.ButtonTextColor;
	            UIBnBookListRefresh.TextFont = mScene.ButtonTextFont;
	            UIBnBookListRefresh.Style = ButtonStyle.Custom;
	            UIBnBookListRefresh.CustomImage = mScene.mButtonImage;
				this.mRoot.AddChildLast(UIBnBookListRefresh);
				
				UIBnBookDelete = new Button();
				UIBnBookDelete.Name = "UIBnBookDelete";
	            UIBnBookDelete.TextColor = mScene.mButtonTextColor;
	            UIBnBookDelete.TextFont = mScene.mButtonTextFont;
	            UIBnBookDelete.Style = ButtonStyle.Custom;
	            UIBnBookDelete.CustomImage = mScene.mButtonImage;
				this.mRoot.AddChildLast(UIBnBookDelete);
				
				UISpBookListParent = new ScrollPanel();
				UISpBookListParent.Name = "UISpBookListParent";
				UISpBookListParent.PanelColor = new UIColor(0,0,0,0);
				UISpBookListParent.ScrollBarVisibility = ScrollBarVisibility.Invisible;
				UISpBookListParent.VerticalScroll = true;
				UISpBookListParent.HorizontalScroll = false;
				this.mRoot.AddChildLast(UISpBookListParent);
				
					// UILpBookList
		            UILpBookList = new ListPanel();
		            UILpBookList.Name = "UILpBookList";
		            UILpBookList.ScrollBarVisibility = ScrollBarVisibility.Invisible;
					this.UISpBookListParent.AddChildFirst(UILpBookList);
				
				/*
				UILbBookInfo = new Label();
				UILbBookInfo.Name = "UILbBookInfo";
				UILbBookInfo.TextColor = new UIColor(0f / 255f, 0f / 255f, 0f / 255f, 255f / 255f);
				UILbBookInfo.BackgroundColor = new UIColor(250f / 255f, 255f / 255f, 250f / 255f, 0f / 255f);
				UILbBookInfo.HorizontalAlignment = HorizontalAlignment.Left;
				UILbBookInfo.VerticalAlignment = VerticalAlignment.Top;
				this.UISpBookListParent.AddChildLast(UILbBookInfo);
				*/
			}
            //this.RootWidget.AddChildLast(mRoot);
			#endregion
			
			
			#region init
			//UILpBookList.FocusStyle = FocusStyle.None;
			//UILpBookList.Focusable = false;
			
			UILpBookList.FocusStyle = FocusStyle.None;
			UILpBookList.Focusable = false;
			
			UISpBookListParent.FocusStyle = FocusStyle.None;
			UISpBookListParent.Focusable = false;
			
			//UILbBookInfo.Font = (mScene.View as PSView).FontSet.Middle;
			
			DragGestureDetector drag = new DragGestureDetector();
			drag.DragDetected += HandleBookListDrag;
			drag.MaxDistance = 10;
			UISpBookListParent.AddGestureDetector(drag);
			
			
			mRoot.KeyEventReceived += HandleListKey;
			UIBnBookListCancel.ButtonAction += mScene.HandleShowMenu;
			UIBnBookDelete.ButtonAction += HandleBookDelete;
			UIBnBookListRefresh.ButtonAction += HandleRefreshBookList;
			
			UIBnBookListCancel.Focusable = false;
			UIBnBookListRefresh.Focusable = false;
			
			mBookListButton = new List<Button>();
			mCurrentBookListItem = 0;
			RefreshBookList();
			#endregion
		}
		
		public override void OnShown()
		{
			//close the reading when open book list
			mScene.mReadingHandler.ReadingClose();
			RefreshBookList();
			//TODO: settings shown should do the same
		}
		
		public override void OnHidden()
		{
			mBookListButton.Clear();
			
			if( UILpBookList.Sections != null )
			{
				UILpBookList.Sections.Clear();
			}
		}
		
		public override void UpdateLayout(LayoutOrientation orientation)
		{
			switch (orientation)
            {
            case LayoutOrientation.Vertical:
				break;
			default:
				float btnPadding = mScene.View.ButtonPadding;
				float btnWidth = mScene.View.ButtonWidth;
				float btnHeight = mScene.View.ButtonHeight;
				float Gap = 45.0f;
				
				/*
				float infoPadding = 50.0f;
				UILbBookInfo.SetPosition(mScene.View.Width/2+Gap,infoPadding);
				UILbBookInfo.SetSize(mScene.View.Width/2-Gap , height);
				UILbBookInfo.Visible = true;
				*/
				
				//book list
				//UIBnBookListCancel.IconImage = mIconCross;
				mRoot.SetPosition(0, 0);
                mRoot.SetSize(mScene.View.Width, mScene.View.Height);
                mRoot.Anchors = Anchors.Top | Anchors.Height | Anchors.Left | Anchors.Width;
               // mRoot.Visible = false;
				{
					float borderPadding = 6.0f;
					float titleHeight = UILbBookListTitle.Font.GetFont().Metrics.Height;
					UILbBookListTitle.SetPosition(borderPadding,borderPadding);
					UILbBookListTitle.SetSize(mScene.View.Width/2-borderPadding-Gap, titleHeight );
					
					UILbBookListCounter.SetPosition(borderPadding,borderPadding);
					UILbBookListCounter.SetSize(mScene.View.Width/2-borderPadding-Gap,titleHeight);					
					
					UIBnBookListCancel.SetPosition( mScene.View.Width-btnWidth-btnPadding, mScene.View.Height-btnHeight-btnPadding );
					UIBnBookListCancel.SetSize(btnWidth, btnHeight);
					
					//UIBnBookListRefresh.IconImage = mIconTriangle;
					UIBnBookListRefresh.SetPosition( mScene.View.Width-btnWidth*2-btnPadding*2, mScene.View.Height-btnHeight-btnPadding );
					UIBnBookListRefresh.SetSize(btnWidth, btnHeight);
					
					UIBnBookDelete.SetPosition(mScene.View.Width-btnWidth*3-btnPadding*3, mScene.View.Height-btnHeight-btnPadding);
					UIBnBookDelete.SetSize(btnWidth, btnHeight);
					
					UIImgBookListBk.SetPosition(0,0);
					UIImgBookListBk.SetSize(mScene.View.Width,UIBnBookListRefresh.Y-btnPadding);
					UIImgBookListBk.Anchors = Anchors.Top | Anchors.Height | Anchors.Left | Anchors.Width;
					UIImgBookListBk.Visible = true;
						
					//
					float height = UIBnBookListCancel.Y - btnPadding - titleHeight - borderPadding*2;
					UISpBookListParent.SetPosition(borderPadding,titleHeight+borderPadding);
					UISpBookListParent.SetSize(mScene.View.Width-borderPadding*2,height);
					UISpBookListParent.PanelWidth = UISpBookListParent.Width;
					UISpBookListParent.PanelHeight = UISpBookListParent.Height;
					UISpBookListParent.Visible = true;
					
						UILpBookList.SetPosition(0, 0);
		                UILpBookList.SetSize(UISpBookListParent.Width, height);
		                UILpBookList.Anchors = Anchors.Top | Anchors.Height | Anchors.Left | Anchors.Width;
		                UILpBookList.Visible = true;
				}
				break;
			}
		}
		
		public override void UpdateLanguage(StreamReader reader)
		{
			String s = reader.ReadLine();
			String[] items = s.Split(',');
			int count = 0;
			if( count < items.Length )
				UILbBookListTitle.Text = items[count++];
			if( count < items.Length )
				UIBnBookDelete.Text = items[count++];
			if( count < items.Length )
				UIBnBookListRefresh.Text = items[count++];
			if( count < items.Length )
			{
				if( Sce.PlayStation.Core.Environment.SystemParameters.GamePadButtonMeaning == GamePadButtonMeaning.CircleIsEnter )
					UIBnBookListCancel.Text = "X " + items[count++];
				else
					UIBnBookListCancel.Text = "○ " + items[count++];
			}
		}
		#endregion
				
		private void HandleListKey(object sender, KeyEventArgs e)
		{
			if( this.Showing || this.Hiding )
				return;
			
			if( e.KeyEventType == KeyEventType.Up )
			{
				switch(e.KeyType)
				{
				case KeyType.Triangle:	//triangle bind to refresh
					RefreshBookList();
					break;
				case KeyType.Square:
					DeleteCurrentBook();
					break;
				case KeyType.Back:		// cross bind to cancel
					mScene.ShowUI(UIType.MAINMENU,UISwitch.ZOOM);
					break;
				case KeyType.Enter:
					if( mCurrentBookListItem < mBookListButton.Count && mCurrentBookListItem >= 0 )
					{
						Button button = mBookListButton[mCurrentBookListItem];
						if( button != null )
							mScene.Handler.ReadingOpen( button.Text );
					}
					break;
					
				case KeyType.Up:
				case KeyType.Left:
					if( mBookListButton == null || mBookListButton.Count == 0 )
						mCurrentBookListItem = 0;
					else if( --mCurrentBookListItem < 0 )
						mCurrentBookListItem = mBookListButton.Count-1;
					UpdateSelectedBookItem();
					break;
					
				case KeyType.Down:
				case KeyType.Right:
					if( mBookListButton == null || mBookListButton.Count == 0 )
						mCurrentBookListItem = 0;
					else if( ++mCurrentBookListItem >= mBookListButton.Count )
						mCurrentBookListItem = 0;
					UpdateSelectedBookItem();
					break;
				case KeyType.L:
					//R/L swtich between local books / downloading list
					mScene.ShowUI(UIType.DOWNLOADS,UISwitch.RIGHT);
					break;
				}
			}
		}
		
		private void HandleBookListDrag(object sender, DragEventArgs e)
		{
			if( this.Showing || this.Hiding )
				return;
			
			DragType drag = mScene.Control.DetectDrag(e.Distance.X,e.Distance.Y);
			//horizontal drag, same as button R
			if( drag == DragType.LEFT )
				mScene.ShowUI(UIType.DOWNLOADS,UISwitch.RIGHT);
		}
		
		private void DeleteCurrentBook()
		{
			IReaderData data = mScene.Data;
			List<BookInfo> filesList = data.BookList;
			if( mCurrentBookListItem >= filesList.Count )
				return;
			
			String file = filesList[mCurrentBookListItem].FileName;
			String info = String.Format( mScene.Language.MsgDeleteBookConfirm, file);
			
			mScene.ConfirmMessageBox(info, ConfirmDeleteBook, file);
		}
		
		private void ConfirmDeleteBook(object target)
		{
			String file = target as String;
			if( mScene.Data.DeleteBook(file) )
			{
				RefreshBookList();
			}
		}
		
		private void HandleRefreshBookList(object sender, TouchEventArgs e)
		{
			RefreshBookList();
		}
				
		private void HandleBookItem(object sender, TouchEventArgs e)
		{
			Button button = sender as Button;
			String [] s = button.Name.Split('.');
			if( s.Length < 2 )
				return;
			int index = Convert.ToInt32(s[1]);
			if( index != mCurrentBookListItem )
			{
				mCurrentBookListItem = index;
				UpdateSelectedBookItem();
			}
			else
			{
				String fileName = button.Text;
				mScene.Handler.ReadingOpen(fileName);
			}
		}
		
		private void HandleBookDelete(object sender, TouchEventArgs e)
		{
			DeleteCurrentBook();
		}
		
		private bool FindHelp(BookInfo info)
		{
			return mScene.IsHelp(info.FileName);
		}
		
		private void RefreshBookList()
		{
			mScene.Data.RefreshBookInfo();
			float width = UILpBookList.Width;
			float x = UILpBookList.X;
			float y = UILpBookList.Y;

			
			UISpBookListParent.RemoveChild( UILpBookList );
			UILpBookList.Dispose();
			UILpBookList = new ListPanel();
			UILpBookList.Width = width;
			UILpBookList.SetPosition(x,y);
			UILpBookList.Visible = true;
			UILpBookList.FocusStyle = FocusStyle.None;
			UILpBookList.Focusable = false;
			UILpBookList.Anchors = Anchors.Top | Anchors.Height | Anchors.Left | Anchors.Width;
			UISpBookListParent.AddChildLast(UILpBookList);
			
			
			FillBookList();

			//after delete
			if( mBookListButton.Count == 0 )
				mCurrentBookListItem = 0;
			else if( mCurrentBookListItem >= mBookListButton.Count )
				mCurrentBookListItem = mBookListButton.Count-1;
			
			UpdateSelectedBookItem();
			//ShowBookList();
		}
		
		private void FillBookList()
		{
			this.UpdateLayout(mScene.Layout);
			mBookCount = 0;
			//init book list
			IReaderData data = mScene.Data;
			List<BookInfo> filesList = data.BookList;
			
			if(filesList == null)
				return;
			
			while(true)
			{
				int helpIndex = filesList.FindIndex( FindHelp );
				if( helpIndex != -1 )
					filesList.RemoveAt(helpIndex);
				else
					break;
			}
			
			int BookCount = filesList.Count;
			//if( BookCount == 0 )
			//	return;
			
			if( LIST_BUTTON_HEIGHT*BookCount >= UISpBookListParent.Height )
				UISpBookListParent.PanelHeight = LIST_BUTTON_HEIGHT*BookCount;
			UISpBookListParent.PanelX = 0;
			UISpBookListParent.PanelY = 0;

			mBookListButton.Clear();
			UILpBookList.SetListItemCreator(BookListItemCreator);
			ListSectionCollection section = new ListSectionCollection();
			

			section.Add( new ListSection("Book List", BookCount) );
			UILpBookList.Sections = section;//.Add( new ListSection("Book List", BookCount) );

			UILpBookList.ShowSection = false;
			UILpBookList.ShowItemBorder = false;
		}
		
		private ListPanelItem BookListItemCreator()
		{
			//force set height, or it will be cliped
			UILpBookList.Height = UISpBookListParent.PanelHeight;
			
			IReaderData data = mScene.Data;
			List<BookInfo> filesList = data.BookList;
			
			ListPanelItem item = new ListPanelItem();
			item.BackgroundColor = mScene.ListItemColor;
			item.SetSize(UILpBookList.Width, LIST_BUTTON_HEIGHT);
			item.Visible = true;
			
			float Gap = 40.0f;
			float ButtonWidth = UILpBookList.Width/2-Gap;
			Button button = new Button();
			button.Name = "BookItem." + mBookCount;
			button.SetPosition(0, 0);
            button.SetSize(ButtonWidth, LIST_BUTTON_HEIGHT);
            button.Anchors = Anchors.Top | Anchors.Bottom | Anchors.Left | Anchors.Right;
            button.Visible = true;
			
			button.Style = ButtonStyle.Custom;
			//button.HorizontalAlignment = HorizontalAlignment.Left;
            button.TextColor = mScene.ListItemTextColor;
            button.TextFont = mScene.ListItemTextFont;
            button.CustomImage = null;
			button.Text = filesList[mBookCount].FileName;
			button.ButtonAction += HandleBookItem;
			button.Focusable = false;
			item.AddChildLast(button);

			
			//add additional info
			Label info = new Label();
			info.Text = "<" + filesList[mBookCount].Title + "> " + (filesList[mBookCount].Size+1023) / 1024 + "K";
			info.Font = mScene.FontSet.Small;
			info.SetPosition(ButtonWidth+Gap*2,0);
			info.Visible = true;
			info.TextColor = mScene.TitleColor;
			info.VerticalAlignment = VerticalAlignment.Middle;
			info.HorizontalAlignment = HorizontalAlignment.Left;
			info.SetSize(ButtonWidth, LIST_BUTTON_HEIGHT);
			item.AddChildLast(info);
			item.Focusable = false;
			
			mBookCount++;
			mBookListButton.Add ( button );
			
			UpdateSelectedBookItem();
			return item;
		}
		
		private void UpdateSelectedBookItem()
		{
			if( mCurrentBookListItem >= mBookListButton.Count || mCurrentBookListItem < 0 )
			{
				UILbBookListCounter.Text = "0/0";
				return;
			}
			
			UILbBookListCounter.Text = Convert.ToString(mCurrentBookListItem+1)+'/'+Convert.ToString(mBookCount);
			
			//Button button = mBookListButton[ mCurrentBookListItem ];
			for(int i = 0; i < mBookListButton.Count; ++i)
			{
				ListPanelItem item = mBookListButton[i].Parent as ListPanelItem;
				if( i == mCurrentBookListItem )
				{
					//mBookListButton[i].CustomImage = null;
					item.BackgroundColor = mScene.ListItemHilightColor;
					EnsureListItemVisible(item, UISpBookListParent);
				}
				else
				{
					//mBookListButton[i].CustomImage = mScene.ListImage;
					item.BackgroundColor = mScene.ListItemColor;
				}
			}
		}
		
	}//class
}